import cv2
import time
import base64
import json
import os
import logging
from threading import Thread, Event
from picamera2 import Picamera2
import paho.mqtt.client as mqtt
from datetime import datetime
from paho.mqtt.client import CallbackAPIVersion

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("Video")

BROKER = "120.46.12.5"
PORT = 1883
TOPIC = "camera/encode_transfrom"
CLIENT_ID = "啊嘞嘞"
USERNAME = "gll"
PASSWORD = "gll55555"

# MQTT 回调函数
def on_connect(client, userdata, flags, reason_code, properties):
    if reason_code == 0:
        logger.info("Connected to MQTT broker")
    else:
        logger.error(f"Failed to connect to MQTT, reason: {reason_code}")

client = mqtt.Client(client_id=CLIENT_ID, callback_api_version=CallbackAPIVersion.VERSION2)
client.username_pw_set(username=USERNAME, password=PASSWORD)
client.on_connect= on_connect
client.connect(BROKER, PORT, 60)
client.loop_start()

class Video:
    def __init__(self):
        self.cap = Picamera2()
        self.stop_event = Event()
        self.frame_count = 0
        self.fps_start = time.time()
        self.fps = 0

        os.makedirs("IMAGES", exist_ok=True)
    
    def setup(self):
        config = self.cap.create_video_configuration(
            main={"size": (320,320)},
            controls={"FrameRate": 30.0}
        )
        self.cap.configure(config)
        self.cap.start()
        time.sleep(1)

    def calculate_fps(self):
        """实时计算FPS"""
        self.frame_count += 1
        elapsed = time.time() - self.fps_start
        if elapsed >= 1.0:
            self.fps = self.frame_count / elapsed
            self.frame_count = 0
            self.fps_start = time.time()

    def online_stream(self):
        while not self.stop_event.is_set():
            frame = self.cap.capture_array("main")
            frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)

            cv2.imshow("Online Stream", frame)
            if cv2.waitKey(1) == ord('q'):
                self.stop_event.set()

    def take_picture(self):
        filename = f"IMAGES/{datetime.now().strftime('%Y%m%d_%H%M%S')}.jpg"
        buffer = self.cap.capture_array("main")
        buffer = cv2.cvtColor(buffer, cv2.COLOR_RGB2BGR)


        cv2.imwrite(filename, buffer)
        logger.info(f"save: successfully {filename}")        


    def run(self):
        self.setup()
        display_thread = Thread(target=self.online_stream, daemon=True)
        display_thread.start()

        try:
            while not self.stop_event.is_set():
                self.calculate_fps()
                key = cv2.waitKey(1)

                if key == ord('t'):
                    self.take_picture()

        except KeyboardInterrupt:
            print("Stop by user")

        finally:
            self.stop_event.set()
            self.cap.stop()
            cv2.destroyAllWindows()
            client.loop_stop()
            client.disconnect()    

if __name__ == "__main__":
    video = Video()
    video.run()